package client_core

import (
	"context"
	"github.com/chicken-team-outside/chicken_transmission/model"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

func initTaskApi(ctx context.Context, group *gin.RouterGroup) {
	initDownloadMgr(ctx, group.Group("/download"))
	initUploadTaskMgr(ctx, group.Group("/upload"))
	group.POST("/cleanup", cleanFinishedTask)
}

type TaskIdsQuery struct {
	Ids []*model.TaskId `json:"ids"`
}

func cleanFinishedTask(ctx *gin.Context) {
	query := new(TaskIdsQuery)
	err := ctx.BindJSON(query)
	if err != nil {
		zap.L().Info("failed to bind query", zap.Error(err))
		BadParameter(ctx)
		return
	}
	if len(query.Ids) > 0 {
		var downloadTaskIds []*model.TaskId
		var uploadTaskIds []*model.TaskId
		for _, id := range query.Ids {
			if id.TaskType == model.TaskType_DownloadDir || id.TaskType == model.TaskType_DownloadFile {
				downloadTaskIds = append(downloadTaskIds, id)
			} else {
				uploadTaskIds = append(uploadTaskIds, id)
			}
		}
		if len(downloadTaskIds) > 0 {
			err = downloadTaskRunnerMgr.DeleteTask(downloadTaskIds)
		}
		if len(uploadTaskIds) > 0 && err == nil {
			err = uploadTaskRunnerMgr.DeleteTask(uploadTaskIds)
		}
	}
	if err == nil {
		Success(ctx, nil, "")
	} else {
		BadRequest(ctx, err.Error())
	}
}
